<?php

/**
 * This is the model class for table "tbl_users".
 *
 * The followings are the available columns in table 'tbl_users':
 * @property integer $id
 * @property string $real_name
 * @property string $password
 * @property string $email
 * @property string $created_date
 * @property string $employeeid
 * @property string $custno
 * @property string $deviceid
 * @property string $privileges
 */
class Users extends CActiveRecord {
    const PRIVILEGE_USER=1;
    const PRIVILEGE_MOBILE_LOGIN=4;
    const PRIVILEGE_SHOW_SSNUMBER=5;
    const PRIVILEGE_SHOW_PAYRATE=6;
    const PRIVILEGE_EMPLOYEE_ADMIN=7;
    const PRIVILEGE_REPORT_SALES=8;
    const PRIVILEGE_SYSTEM_MENU=9;
    const PRIVILEGE_UNLOCK_INVOICE=10;
    public $privileges;
   
    const QUESTION_SPORT=1;
    const QUESTION_BORN_PLACE=2;

    /**
     * Returns the static model of the specified AR class.
     * @return Users the static model class
     */
    public static function model($className=__CLASS__) {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName() {
        return 'tbl_users';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules() {

        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('id, real_name,email, created_date,utype', 'required'),
            array('id, employeeid, deviceid', 'length', 'max' => 4),
            array('real_name, password', 'length', 'max' => 50),
            array('email', 'length', 'max' => 100),
            array('custno', 'length', 'max' => 7, 'min' => 4),
            // array('custno', 'checkCustnoEmpno'),
            array('utype', 'userTypeCheck'),
            array('employeeid', 'exist', 'className' => 'Employees', 'attributeName' => 'empno'),
            array('custno', 'exist', 'className' => 'Customers', 'attributeName' => 'custno'),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('id, real_name, password, email, created_date, employeeid, custno, deviceid', 'safe', 'on' => 'search'),
        );
    }

    public function checkCustnoEmpno($attribute, $params) {
        if ($this->custno != NULL && $this->employeeid != NULL) {
            $error = 'A user can not have both employee number and customer number';
            $this->addError('custno', $error);
            $this->addError('employeeid', $error);
        }
    }

    public function userTypeCheck($attribute, $params) {
        switch ($this->utype) {
            case 1 :
            case 2 :
                $error = 'This type of user must have employee number';
                if (!$this->employeeid)
                    $this->addError('employeeid', $error);
                break;
            case 3: $error = 'This type of user must have customer number';
                if (!$this->custno)
                    $this->addError('custno', $error);
                break;
        }
    }

    /**
     * @return array relational rules.
     */
    public function relations() {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
            'employee'=>array(self::BELONGS_TO,'Employees','employeeid'),
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
        return array(
            'id' => 'ID',
            'real_name' => 'Real Name',
            'password' => 'Password',
            'email' => 'Email',
            'created_date' => 'Created Date',
            'employeeid' => 'Employee Number',
            'custno' => 'Customer number',
            'deviceid' => 'Deviceid',
            'privileges' => 'Privileges',
            'utype' => 'User type'
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search() {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.

        $criteria = new CDbCriteria;

        $criteria->compare('id', $this->id, true);
        $criteria->compare('real_name', $this->real_name, true);
        $criteria->compare('password', $this->password, true);
        $criteria->compare('email', $this->email, true);
        $criteria->compare('created_date', $this->created_date, true);
        $criteria->compare('employeeid', $this->employeeid, true);
        $criteria->compare('custno', $this->custno, true);
        $criteria->compare('deviceid', $this->deviceid, true);

        return new CActiveDataProvider($this, array(
                    'criteria' => $criteria,
                ));
    }
    
    public function beforeValidate() {

        //ecrypt password before save to db
        if ($this->isNewRecord) {
            $num = Yii::app()->db->createCommand('select max(cast(id as unsigned)) from tbl_users')->queryScalar();
            if ($num) {
                $this->id = str_pad($num + 1, 4, '0', STR_PAD_LEFT);
            } else {
                return false;
            }
        }
        $oldModel = Users::model()->findByPk($this->id);
        if ($oldModel == NULL) {
            $this->password = md5($this->password);
        } else {
            if ($this->password != $oldModel->password && $this->password != '') {
                $this->password = md5($this->password);
            } else {
                $this->password = $oldModel->password;
            }
        }



        $this->created_date = DateUtil::getDefaultCurrentDateTime();
        return parent::beforeValidate();
    }

    public function beforeSave() {

        //create new useraccess


        $userAccess = Useraccess::model()->find('user_id=:id', array(
            'id' => $this->id,
                ));

        if ($userAccess != null) {
            if ($this->privileges != NULL)
                $userAccess->privilege = $this->privileges;
            $userAccess->type = $this->utype;
        }else {
            $userAccess = new Useraccess;
            $userAccess->user_id = $this->id;
            $userAccess->type = $this->utype;
            if ($this->privileges != NULL)
                $userAccess->privilege = $this->privileges;
        }
        $userAccess->save();

        //  $userAccess->save();


        return parent::beforeSave();
    }

    public function getUserAccess() {
        return Useraccess::model()->findByPk($this->id);
    }

    public function getPrivilegeList() {

        return array(
            self::PRIVILEGE_USER => 'Manage User',
            self::PRIVILEGE_MOBILE_LOGIN => 'Mobile Login',
            self::PRIVILEGE_SHOW_SSNUMBER => 'View Social Sercurity Number',
            self::PRIVILEGE_EMPLOYEE_ADMIN => 'Employee Admin',
            self::PRIVILEGE_SHOW_PAYRATE => 'View Pay Rate',
            self::PRIVILEGE_REPORT_SALES => 'Show Sales Report',
            self::PRIVILEGE_SYSTEM_MENU => 'Access System Menu',
            self::PRIVILEGE_UNLOCK_INVOICE => 'Unlock Invoice',
        );
    }

    public function getPrivilegeData() {
        if ($this->userAccess != NULL)
            return explode(',', $this->userAccess->privilege);
        return NULL;
    }

    public function checkPermission($url, $userid=NULL) {
        if ($userid == NULL) {
            $userid = $this->id;
        }
        $model = self::model()->findByPk($userid);
        $fullurl = $url . '/index';
     if(!isset( $model->userAccess->privilege)){
            Yii::app()->getController()->redirect(array('site/login'));

        }
          
         $privilege = $model->userAccess->privilege;
         $privilege = unserialize($privilege);
        $permissions = Permissions::model()->findAll();
        $permissionsList = CHtml::listData($permissions, 'id', 'link');

        if (in_array($fullurl, $permissionsList)) {
            $permissionID = array_search($this->id, $permissionsList);
        } elseif (in_array($url, $permissionsList)) {
            $permissionID = array_search($url, $permissionsList);
        } else return true;
        if(is_array($privilege)){
            return in_array($permissionID, $privilege);    
        }
        
    }

    public function getCurrentPrivilegeList() {
        $privileges = Yii::app()->db->createCommand('select privilege from tbl_useraccess where user_id=:id')->queryScalar(array('id' => $this->id));
        $selected = array();
        if ($privileges != NULL && count($privileges) > 0)
            $selected = explode(',', $privileges);

        return CHtml::checkBoxList('Users[privileges]', $selected, $this->getPrivilegeList(), array(
                ));
    }

    public function getQuestionList() {
        return array(
            self::QUESTION_SPORT => 'What is your farvorite sport',
            self::QUESTION_BORN_PLACE => 'Where did you born',
        );
    }

    public function getEmployeeList() {
        $data = Yii::app()->db->createCommand('select firstname,lastname,empno from tbl_employees')->queryAll();
        $rs = array();
        $rs[''] = "N/A";
        if (count($data) > 0) {
            foreach ($data as $item) {
                $rs[$item['empno']] = $item['firstname'] . ' ' . $item['lastname'];
            }
        }
        return $rs;
    }

    public function getCustomerList() {
        $data = Yii::app()->db->createCommand('select lastname,custno from tbl_customers')->queryAll();
        $rs = array();
        $rs[''] = "N/A";
        if (count($data) > 0) {
            foreach ($data as $item) {
                $rs[$item['custno']] = $item['lastname'];
            }
        }
        return $rs;
    }

    public static function getUserNameByEmail($email) {
        $name = Yii::app()->db->createCommand('select real_name from tbl_users where email=:email')->bindValue('email', $email)->queryRow();
        if ($name != false) {
            return $name['real_name'];
        }
        return 'No Name';
    }

    function getUserByPermission($permission) {
        $users = Yii::app()->db->createCommand('select u.email from tbl_useraccess ua 
        join tbl_users u on u.id=ua.user_id
        where find_in_set(:permission,ua.privilege)>0')->bindValues(array(
                    'permission' => $permission
                ))->queryAll();


        $rs = array();
        $s = '';
        if ($users != NULL && count($users > 0)) {
            foreach ($users as $i => $item) {

                $s.=$item['email'] . ',';
            }
        }

        $rs = explode(',', $s);
        return $rs;
    }

    public static function getTotalAssignedDispatch($empno) {
        if ($empno == NULL)
            return 0;
        $totalDispatch = Yii::app()->db->createCommand('select count(*) from tbl_dispatch_tech where
                                        enddate is not NULL and endtime is not NULL
                                        and empno=:empno')->bindValue('empno', $empno)->queryScalar();
        if ($totalDispatch !== NULL) {
            return $totalDispatch;
        }
    }

    public static function getUserNameById($id) {
        $name = Yii::app()->db->createCommand('select real_name from tbl_users where id =:id')->bindParam('id', $id)->queryScalar();
        return $name;
    }

}
